package cn.cms.aspect;

import cn.cms.annotation.SystemLogAnno;
import cn.cms.service.SysLogService;
import cn.cms.model.SysLog;
import cn.cms.model.SysUser;
import cn.cms.util.SessionUtil;
import cn.cms.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

@Aspect
@Component
public class SystemLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

    @Autowired
    public SysLogService sysLogService;

    @Pointcut("execution( * cn.cms.controller..*.*(..))")
    public void controllerAspect() {

    }

    @After("controllerAspect()")
    public void after(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        SysUser sysUser = SessionUtil.getUserSession(request);
        Map<String, String[]> params = request.getParameterMap();
        if (sysUser != null) {
            SysLog systemLog = new SysLog();
            systemLog.setLoginName(sysUser.getLoginName());
            systemLog.setSrcIp(SystemLogAspect.getIpAddr(request));
            systemLog.setRealName(sysUser.getRealName());
            try {

                String targetName = joinPoint.getTarget().getClass().getName();
                String methodName = joinPoint.getSignature().getName();
                Object[] arguments = joinPoint.getArgs();
                Class targetClass = Class.forName(targetName);
                Method[] methods = targetClass.getMethods();
                String operationType = "";
                String operationName = "";
                String operationParams = "";

                for (Method method : methods) {

                    if (methodName.equals(method.getName()) && method.isAnnotationPresent(SystemLogAnno.class)) {


                        Class[] classes = method.getParameterTypes();
                        if (classes.length == arguments.length) {

                            logger.info("Logging user operation.");
                            Map<String, String> tmpParams = Maps.newLinkedHashMap();
                            for (Map.Entry<String, String[]> entry : params.entrySet()) {

                                if (entry.getValue().length > 1) {

                                    StringBuilder stringBuilder = new StringBuilder();
                                    for (int i = 0; i < entry.getValue().length; i++) {

                                        stringBuilder.append(entry.getValue()[i]).append(",");
                                    }

                                    tmpParams.put(entry.getKey(), StringUtils.strip(stringBuilder.toString(), ","));

                                } else {

                                    tmpParams.put(entry.getKey(), entry.getValue()[0]);
                                }

                                // 要把密码隐去
                                if (entry.getKey().toLowerCase().contains("password")) {
                                    tmpParams.put(entry.getKey(), "***");
                                }

                            }
                            operationParams = JSON.toJSONString(tmpParams);
                            operationType = method.getAnnotation(SystemLogAnno.class).operationType();
                            operationName = method.getAnnotation(SystemLogAnno.class).operationName();

                            // 如果是“更新或者新增”类型，要把密码隐去
                            if (SystemLogAnno.ADD.equals(operationType)) {
                                operationType = SystemLogAnno.ADD;
                                operationName = "新增-" + operationName;
                            } else if (SystemLogAnno.UPD.equals(operationType)) {
                                operationType = SystemLogAnno.UPD;
                                operationName = "修改-" + operationName;
                            } else if (SystemLogAnno.ADDORUPD.equals(operationType)) {
                                if (StringUtil.isSpaceOrNull(tmpParams.get("id"))) {
                                    operationType = SystemLogAnno.ADD;
                                    operationName = "新增-" + operationName;
                                } else {
                                    operationType = SystemLogAnno.UPD;
                                    operationName = "修改-" + operationName;
                                }
                            } else if (SystemLogAnno.DEL.equals(operationType)) {
                                operationType = SystemLogAnno.DEL;
                                operationName = "删除-" + operationName;
                            }

                            systemLog.setDateAdd(new Date());
                            systemLog.setType(operationType);
                            systemLog.setName(operationName);
                            systemLog.setParams(operationParams);
                            sysLogService.save(systemLog);
                            logger.info("Logging user operation finished.");
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("记录操作日志异常,异常信息:{}", e.getMessage());
            }
        }
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }
        return ip;
    }

}
